package com.eduction.controller;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.eduction.bean.SessionUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.eduction.common.AppConfig;
import com.eduction.common.ReturnCode;
import com.eduction.common.UploadUtil;
import com.eduction.modules.system.entity.FileDownload;
import com.eduction.resource.BaseController;
import com.eduction.service.FileDownloadService;


/**
 * 文件上传
 * @author bcb
 *
 */
@Controller
@RequestMapping("/upload")
public class UploadController extends BaseController{

	static final Log logger = LogFactory.getLog(UploadController.class);
	
	@Autowired
	private UploadUtil uploadUtil;
	
	@Autowired
	private AppConfig appconfig;
	

	@Autowired
	private FileDownloadService fileDownloadService;

	/**
	 * 图片上传
	 * @param Filedata
	 * @return
	 */
	@RequestMapping(value="/pic" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> uploadPhoto(
			@RequestParam("pic")MultipartFile Filedata
			){
		try {

			if(Filedata.getSize()/1024>appconfig.getPicSize()*1024){
				return toResponse(null,ReturnCode.FILE_TYPE_NOT_MATCH,"图片大小超出上限");
			}
			String str=uploadUtil.uploadpic(Filedata);
			if("22".equals(str)){
				return toResponse(null,ReturnCode.FILE_TYPE_NOT_MATCH,"文件类型有误");
			}
			return toResponse(str,ReturnCode.SUCCESS,null);
		} catch (Exception e) {
			logger.error("文件上传失败", e);
			return toResponse(null,ReturnCode.FAIL,"图片上传失败");
		}
	}
	
	
	/**
	 * 文件上传
	 * @param filedata
	 * @return
	 */
	@RequestMapping(value="/uploadfile" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> uploadFile(
			@RequestParam("file")MultipartFile filedata){
		try {
			String returnDatasUrl = null;
	  		String datasfile = appconfig.getFilePath();

	  		/*//取得可上传的文件类型
	  		List<String>fileTypes = arrayToList(appconfig.getFileType().split(","));*/

	  		String fileName = filedata.getOriginalFilename();
	  		//获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名
	  		String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
	  		//对扩展名进行小写转换
	  		ext = ext.toLowerCase();
	  		/*//新的文件名
	  		String newFileName = new SimpleDateFormat("yyyyMMddHHmmssms").format(new Date()) +
	  				(int)(Math.random()*10000) + "." + ext;*/
	  		File file = null;
	  		/*if(!"pdf".equals(ext)){
	  			return toResponse(null,ReturnCode.FILE_TYPE_NOT_MATCH,"该文件类型不允许");
	  		}*/
	  		Long examSize=filedata.getSize();
	  		if(1.0*examSize/1024/1024> 30720 ){
	  			return toResponse(null,ReturnCode.FILE_SIZE_TOO_LONG,"文件大小超出限定上限");
	  		}

	  		Calendar cal=Calendar.getInstance();
            int y=cal.get(Calendar.YEAR);
            int m=cal.get(Calendar.MONTH)+1;
            int d=cal.get(Calendar.DATE);
            Long nowTime=new Date().getTime();
            String pathbig=datasfile+y+"/"+m+"/"+d+"/"+nowTime+"/"+fileName;
            file=new File(pathbig);
     		if(!file.exists()){
     			file.getParentFile().mkdirs();
     			file.createNewFile();
     		}
     		filedata.transferTo(file);
		    returnDatasUrl =y+"/"+m+"/"+d+"/"+nowTime+"/"+fileName;
		    Map<String, Object> resMap = new HashMap<>();
			resMap.put("fileName", fileName);
			resMap.put("url", returnDatasUrl);
			return toResponse(resMap,ReturnCode.SUCCESS,null);
		} catch (Exception e) {
			logger.error("文件上传失败", e);
			return toResponse(null,ReturnCode.FAIL,"文件上传失败");
		}
	}
	
	   private List<String> arrayToList(String[] strs){
	    	List<String> list=new ArrayList<String>();
	    	if(strs.length>0){
	    		for(int a =0;a<strs.length;a++){
	    			list.add(strs[a].toString().trim());
	    		}
	    	}
			return list;
	    	
	    }
	   /**
		 * 下载文档
		 * @param request
		 * @param response
		 * @param
		 * @return
		 */
		@RequestMapping(value="downloadFile" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8", method=RequestMethod.GET)
		@ResponseBody
		public void downloadFile(HttpServletRequest request,HttpServletResponse response){
			String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
			if(StringUtils.isEmpty(user_type)){
				return;
			}
			try {
				FileDownload f = fileDownloadService.queryFileDownload();
				if(null==f){
					return ;
				}
				//获取网站部署路径(通过ServletContext对象)，用于确定下载文件位置，从而实现下载  
		        String path = appconfig.getFilePath();  
		        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型  
		        String filepath= f.getS_filepath();
		        String filename=filepath.substring(filepath.lastIndexOf("/")+1, filepath.length());
		        filename = java.net.URLEncoder.encode(filename, "UTF-8");
		        
		        response.setHeader("Content-Type","application/msexcel");
		        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filename));
		        response.setContentType("application/vnd.ms-excel;charset=utf-8");
		        
		        ServletOutputStream out;  
		        //通过文件路径获得File对象(假如此路径中有一个download.pdf文件)  
		        File file = new File(path +filepath);  
		  
		            FileInputStream inputStream = new FileInputStream(file);  
		  
		            //3.通过response获取ServletOutputStream对象(out)  
		            out = response.getOutputStream();  
		            try {
				         byte[] buffer = new byte[1024];  
				        /* while (b != -1){  
				            b = inputStream.read(buffer);  
				            //4.写到输出流(out)中  
				            out.write(buffer,0,b);  
				         } */
				         int count = 0;
				         while ((count = inputStream.read(buffer)) > 0) {
				        	 out.write(buffer, 0, count);
				         }
					} catch (Exception e) {
						logger.info("下载文件异常", e);
					}finally{
						inputStream.close();  
			            out.close();  
			            out.flush(); 
					}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
}
